﻿using System;
using System.Collections.Generic;
using System.Management;

namespace SVNManagementAddIn
{
    class GroupHelper
    {
        #region 组管理

        /// <summary>
        /// 创建组
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static bool CreateGroup(string name)
        {
            try
            {
                var group = new ManagementClass(VisualSVN.ROOT, VisualSVN._Group, null);
                ManagementBaseObject @params = group.GetMethodParameters("Create");

                @params["Name"] = name.Trim();
                @params["Members"] = new object[] { };

                group.InvokeMethod("Create", @params, null);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 读取指定组里的成员
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static List<ManagementBaseObject> GetGroupMembersObject(string name)
        {
            var listMembers = new List<ManagementBaseObject>();
            var group = new ManagementClass(VisualSVN.ROOT, VisualSVN._Group, null);
            ManagementObject instance = group.CreateInstance();
            if (instance != null)
            {
                instance.SetPropertyValue("Name", name.Trim());
                ManagementBaseObject @params = instance.InvokeMethod("GetMembers", null, null);
                if (@params != null)
                {
                    var members = @params["Members"] as ManagementBaseObject[];
                    if (members != null)
                    {
                        foreach (ManagementBaseObject member in members)
                        {
                            listMembers.Add(member);
                        }
                    }
                }
            }
            return listMembers;
        }

        /// <summary>
        /// 读取指定组里的成员名称
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static List<string> GetGroupMembersName(string name)
        {
            List<string> listMembers = new List<string>();
            var group = new ManagementClass(VisualSVN.ROOT, VisualSVN._Group, null);
            ManagementObject instance = group.CreateInstance();
            if (instance != null)
            {
                instance.SetPropertyValue("Name", name.Trim());
                ManagementBaseObject @params = instance.InvokeMethod("GetMembers", null, null); //通过实例来调用方法
                if (@params != null)
                {
                    var members = @params["Members"] as ManagementBaseObject[];
                    if (members != null)
                    {
                        foreach (ManagementBaseObject member in members)
                        {
                            listMembers.Add(member["Name"].ToString());
                        }
                    }
                }
            }
            return listMembers;
        }

        /// <summary>
        /// 递归获取仓库下的所有人员
        /// </summary>
        /// <param name="groupName"></param>
        /// <returns></returns>
        public static List<string> GetGroupRecursiveUsersName(string groupName)
        {
            List<string> results = new List<string>();
            string[] groups = groupName.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string group in groups)
            {
                try
                {
                    List<ManagementBaseObject> groupMembers = GetGroupMembersObject(group);
                    ManagementClass groupClass = new ManagementClass(VisualSVN.ROOT, VisualSVN._Group, null);

                    // 组，获取所有组员
                    foreach (ManagementBaseObject member in groupMembers)
                    {
                        if (member.ClassPath.ClassName.Equals(VisualSVN._Group))
                        {
                            results.AddRange(GetGroupRecursiveUsersName(member["Name"].ToString()));
                        }
                        else
                        {
                            results.Add(member["Name"].ToString());
                        }
                    }
                }
                catch
                {
                    // 用户，直接添加名称
                    results.Add(group);
                }

            }
            return results;
        }

        /// <summary>
        /// 设置组拥有的用户
        /// </summary>
        /// <param name="groupName"></param>
        /// <param name="userNames"></param>
        /// <param name="operTypes"></param>
        /// <returns></returns>
        public static bool SetGroupMembers(string groupName, string userNames, string operTypes)
        {
            try
            {
                List<string> listMembersName = GetGroupMembersName(groupName);
                List<ManagementBaseObject> listMembers = new List<ManagementBaseObject>();

                string[] names = userNames.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                if (operTypes == "添加成员")
                {
                    foreach (string name in names)
                    {
                        if (!listMembersName.Contains(name))
                            listMembersName.Add(name);
                    }
                }
                else if (operTypes == "删除成员")
                {
                    foreach (string name in names)
                    {
                        listMembersName.Remove(name);
                    }
                }

                foreach (string name in listMembersName)
                {
                    ManagementObject account;
                    try
                    {
                        // 先判断是否是组
                        account = new ManagementClass(VisualSVN.ROOT, VisualSVN._Group, null).CreateInstance();
                        GetGroupMembersName(name);
                    }
                    catch
                    {
                        // 如果不是组就判断是用户
                        account = new ManagementClass(VisualSVN.ROOT, VisualSVN._User, null).CreateInstance();
                    }
                    if (account != null)
                    {
                        account.SetPropertyValue("Name", name);
                        listMembers.Add(account as ManagementBaseObject);
                    }
                }
                var group = new ManagementClass(VisualSVN.ROOT, VisualSVN._Group, null);
                ManagementObject instance = group.CreateInstance();
                if (instance != null)
                {
                    instance.SetPropertyValue("Name", groupName.Trim());

                    ManagementBaseObject @params = instance.GetMethodParameters("SetMembers");

                    @params["Members"] = listMembers.ToArray();

                    instance.InvokeMethod("SetMembers", @params, null);
                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        /// 删除组
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static bool DeleteGroup(string name)
        {
            try
            {
                var group = new ManagementClass(VisualSVN.ROOT, VisualSVN._Group, null);
                ManagementBaseObject @params = group.GetMethodParameters("Delete");

                @params["Name"] = name.Trim();

                group.InvokeMethod("Delete", @params, null);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        #endregion
    }
}
